package logic

import (
	"context"
	"goods_srv/global"
	"goods_srv/goods_proto"
	"goods_srv/model"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// 获取轮播图列表
func (g *GoodsServer) BannerList(ctx context.Context, in *goods_proto.Empty) (*goods_proto.BannerListResponse, error) {
	bannerListResponse := goods_proto.BannerListResponse{}
	var banner []model.Banner
	tx := global.DB.Find(&banner)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "查询失败")
	}
	bannerListResponse.Total = int32(tx.RowsAffected)
	var bannerResponse []*goods_proto.BannerResponse
	for _, m := range banner {
		bannerResponse = append(bannerResponse, &goods_proto.BannerResponse{
			Id:    m.ID,
			Index: m.Index,
			Image: m.Image,
			Url:   m.Url,
		})
	}
	bannerListResponse.Data = bannerResponse
	return &bannerListResponse, nil
}

// 添加轮播图
func (g *GoodsServer) CreateBanner(ctx context.Context, in *goods_proto.BannerRequest) (*goods_proto.BannerResponse, error) {
	banner := model.Banner{
		Image: in.Image,
		Url:   in.Url,
		Index: in.Index,
	}
	tx := global.DB.Save(&banner)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "新增轮播图失败")
	}
	return &goods_proto.BannerResponse{Id: banner.ID}, nil
}

// 删除轮播图
func (g *GoodsServer) DeleteBanner(ctx context.Context, in *goods_proto.BannerRequest) (*goods_proto.Empty, error) {
	if result := global.DB.Delete(&model.Banner{}, in.Id); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "轮播图不存在")
	}
	return &goods_proto.Empty{}, nil
}

// 修改轮播图
func (g *GoodsServer) UpdateBanner(ctx context.Context, in *goods_proto.BannerRequest) (*goods_proto.Empty, error) {
	var banner model.Banner
	if result := global.DB.First(&banner, in.Id); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "轮播图不存在")
	}
	if in.Image != "" {
		banner.Image = in.Image
	}
	if in.Url != "" {
		banner.Url = in.Url
	}
	if in.Index != 0 {
		banner.Index = in.Index
	}
	tx := global.DB.Updates(&banner)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "修改轮播图失败")
	}
	return &goods_proto.Empty{}, nil
}
